package com.boot.utils;

import com.boot.entity.Dept;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class MyMessageConverter implements HttpMessageConverter<Dept> {
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return true;
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return true;
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON);
        return list;
    }

    @Override
    public Dept read(Class<? extends Dept> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        System.out.println("MyMessageConverter.read");
        InputStream inputStream = inputMessage.getBody();
        byte[] bytes = new byte[1024];
        inputStream.read(bytes);
        ObjectMapper objectMapper = new ObjectMapper();
        Dept dept = objectMapper.readValue(bytes, Dept.class);
        dept.setDnum(3);
        return dept;
    }

    @Override
    public void write(Dept dept, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        System.out.println("MyMessageConverter.write");
        dept.setDnum(5);
        OutputStream outputStream = outputMessage.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(dept);
        outputStream.write(s.getBytes());
        outputStream.flush();
    }
}
